<script lang="ts" setup>
import { inject, onMounted, ref } from 'vue'
import { FormItem, key } from '../../types/form.type'
import Schema from 'async-validator'
import mitter from '../../util/mitter'

defineOptions({
  name: 'SFormItem',
})

const props = defineProps<{ label: string; prop: string }>()

const formData = inject(key)

const errInfo = ref('')

const validator = () => {
  if (!formData?.rules) return Promise.resolve({ res: true })

  const source = formData.model[props.prop]
  const rules = formData.rules[props.prop]
  const schema = new Schema({ [props.prop]: rules })

  return schema.validate({ [props.prop]: source }, (err) => {
    if (err) {
      errInfo.value = err[0].message || `请输入${props.label}`
      return Promise.reject({ res: false })
    } else {
      errInfo.value = ''
    }
  })
}

onMounted(() => {
  if (formData?.rules) {
    mitter.on('validator', validator)
  }
  mitter.emit('addFormItem', o)
})

const o: FormItem = { validator }

defineExpose(o)
</script>

<template>
  <div class="S-form-item">
    <label v-if="label" class="S-form-item__label">{{ props.label }}</label>
    <slot />

    <p class="S-form-item__error" v-if="errInfo">{{ errInfo }}</p>
  </div>
</template>
